<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\TallyClassModel;
use App\V3\V3_2_7\Models\TallyModel;
use App\Helper\Utils\TimeUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use function AlibabaCloud\Client\json;
use Illuminate\Support\Facades\DB;

class TallyController extends BaseController
{
    /**
     * 记账列表
     * @param Request $request
     * AUTHOR  : Chen
     * DateTime: 2022/3/19 10:08
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'type' => [
                'required',
                'integer',
                Rule::In([0, 1, 2]),
            ],//收支类型：0-收入 1-支出 2-全部
        ],[
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
            'type.required' => '参数`type`缺失',
            'type.integer' => '参数`type`仅能为数字',
            'type.in' => '参数`type`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!$this->isShareTally() && $this->getMainUserId() != $this->getUserId()){
            $condition[] = ['user_id','=',$this->getUserId()];
        }else{
            $condition[] = ['main_id','=',$this->getMainUserId()];
        }
        if($data['type']!=2){
            $condition[] = ['type','=',$data['type']];
        }

        if(!empty($data['operator_id'])){
            $condition[] = ['user_id','=',$data['operator_id']];
        }
        $tallyClassInfo  = [];
        if(!empty($data['tally_name'])){
            $tallyClassInfo = TallyClassModel::query()->select('id','name')
                ->where(['main_id' =>$this->getMainUserId()])
                ->where(['name' => $data['tally_name']])->first();
            if(empty($tallyClassInfo)){
                $condition[] = ['tally_class_name','=',$data['tally_name']];
            }
        }

        //查询
        $model = TallyModel::query()->select('a.*','b.nickname')
            ->from('tally as a')
            ->leftJoin('admin as b','b.id','=','a.user_id')
            ->where($condition)
            ->where(function($query)use($tallyClassInfo , $data){
                if(!empty($tallyClassInfo)){
                    $query->orWhere('tally_class_id','=', $tallyClassInfo['id']);
                    $query->orWhere('tally_class_name','=', $tallyClassInfo['name']);
                }elseif(empty($tallyClassInfo) && !empty($data['tally_name'])){
                    if($data['tally_name'] != '采购'){
                        $query->where('tally_class_id','=', '');
                    }
                }
            })
            ->where('a.delete_flag', 0)
            ->orderBy('a.id','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
            //$tallyId = [];
            if(!empty($model['data'])){
                foreach ($model['data'] as &$mVal){
                    //$tallyId[]= $mVal['id'];
                    if(!empty($mVal['tally_class_id']) && !empty($tallyClassInfo['id'])){
                        if($mVal['tally_class_id'] == $tallyClassInfo['id']){
                            $mVal['tally_class_name'] = $tallyClassInfo['name'];
                        }
                    }elseif(!empty($mVal['tally_class_id']) && empty($data['tally_name'])){
                        $mVal['tally_class_name'] = TallyClassModel::query()
                            ->where(['main_id' =>$this->getMainUserId()])
                            ->where(['id' => $mVal['tally_class_id']])->value('name')??$mVal['tally_class_name'];
                    }
                }
            }
            $model['income_total_money'] = TallyModel::select(DB::raw('SUM(money) AS income_total_money'))
            ->where($condition)
          /*  ->where(function($query)use($tallyId){
                if(!empty($tallyId)){
                    $query->whereIn('id',$tallyId);
                }
            })*/
            ->where([
                'delete_flag' => 0,
                'type'=>0
            ])->first()['income_total_money']??0;
            //DB::enableQueryLog();
            $model['expend_total_money'] = TallyModel::select(DB::raw('SUM(money) AS expend_total_money'))
            ->where($condition)
           /* ->where(function($query)use($tallyId){
                if(!empty($tallyId)){
                    $query->whereIn('id',$tallyId);
                }
            })*/
            ->where([
                'delete_flag' => 0,
                'type'=>1
            ])->first()['expend_total_money']??0;
            //dump_dug(DB::getQueryLog());
        return $this->success($model);
    }

    /**
     * 详细
     * @param Request $request
     * AUTHOR  : Chen
     * DateTime: 2022/3/19 10:09
     * @return \Illuminate\Http\JsonResponse
     */
    public function find(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//记账分类主键id
        ],[
            'id.required' => '记账标识id缺失',
            'id.integer' => '记账标识id仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $model = TallyModel::find($data['id']);
        $model['tally_class_name'] = TallyClassModel::query()->where(['id'=>$model['tally_class_id']])->value('name')??$model['tally_class_name'];
        return $this->success($model);
    }

    /**
     * 新建
     * @param Request $request
     * AUTHOR  : Chen
     * DateTime: 2022/3/19 10:17
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'tally_class_name' =>'required',//记账类型名称
            'type' => [
                'required',
                'integer',
                Rule::In([0, 1]),
            ],//收支类型：0-收入 1-支出
            'money' => 'numeric'
        ],[
            'tally_class_name.required' => '请填写记账类型名称',
            'type.required' => '请选择收支类型',
            'type.integer' => '您选择的收支类型不合法，请重试',
            'type.in' => '您选择的收支类型不合法，请重试',
            'money.numeric' => '金额仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['created_at'] = strtotime(date("Y-m-d",time()));
        $data['add_time'] = time();
        $data['proof_image'] = empty($data['proof_image'])?'':$data['proof_image'];
        $data['order_no'] = 'HM'.$data['main_id'].TimeUtil::getMillisecond();
        $id = TallyModel::insertGetId($data);
        $logReg = !empty($data['type'])?'支出':'收入';
        $logData = '类型名称:'.$data['tally_class_name'].$logReg.'金额为：'.$data['money'].'元';
        $this->log('添加记账', $data, $logData);
        return $this->success($id);
    }

    /**
     * 编辑
     * @param Request $request
     * AUTHOR  : Chen
     * DateTime: 2022/3/19 10:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//记账分类主键id
            'tally_class_name' =>'required',//记账类型名称
            'type' => [
                'required',
                'integer',
                Rule::In([0, 1]),
            ],//收支类型：0-收入 1-支出
            'money' =>'numeric',//  记账金额
        ],[
            'id.required' => '记账分类主键id缺失',
            'id.integer' => '记账分类主键id异常',
            'tally_class_name.required' => '请填写记账类型名称',
            'type.required' => '请选择收支类型',
            'type.integer' => '您选择的收支类型不合法，请重试',
            'type.in' => '您选择的收支类型不合法，请重试',
            'money.numeric' => '金额仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('',$info);
        }
        TallyModel::where('id',$data['id'])->update($data);
        $logData = '类型名称:'.$data['tally_class_name'].'信息已更改！';
        $this->log('编辑记账', $data, $logData);
        return $this->success();
    }

    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required',//记账分类主键id   多条用逗号分隔
        ],[
            'id.required' => '记账分类主键id缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $tallyList = TallyModel::select('tally_class_name')
        ->whereIn('id',$id=explode(',',$data['id']))->get()->toArray();
        if(!empty($tallyList)){
        $className=join('、',array_column($tallyList, 'tally_class_name'));
        $logData = '记账类型名称：'.$className.' 已删除！';
        TallyModel::destroy(explode(',',$data['id']));
        $this->log('删除记账', $data, $logData);
        }
        return $this->success();

    }


    /**
     * 选择记账类型
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|unknown
     */
    public function chooseTallyName(Request $request)
    {
        if($this->getMainUserId() == $this->getUserId() || $this->isShareCustomer()) {
            $condition['main_id'] = $this->getMainUserId();
        }else {
            $condition['user_id'] = $this->getUserId();
        }
        $list = TallyModel::select('tally_class_id','tally_class_name')
        ->where([
            'delete_flag' => 0,
        ])->where($condition)
        ->distinct()->get()->toArray();
        if(!empty($list)){
            foreach ($list as &$lVal){
                if(!empty($lVal['tally_class_id'])){
                    $lVal['tally_class_name'] = TallyClassModel::query()
                        ->where(['id' => $lVal['tally_class_id']])->value('name')??$lVal['tally_class_name'];
                }
            }
        }
        $list = array_unique(array_column($list, 'tally_class_name'));
        $list = !empty($list[0])?array_values($list):[];
        return success($list);
    }
}
